package com.tanhua.bg.login.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.bg.login.config.LoginThreadLocal;
import com.tanhua.bg.login.mapper.LoginMapper;
import com.tanhua.bg.login.pojo.Login;
import com.tanhua.bg.login.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class LoginService  {


    @Autowired
    private LoginMapper  loginMapper;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


   @Value("${jwt.secret}")
   private String secret;

    // redis的前缀
   private static final String REDIS_KEY_PREFIX = "LOGIN_CAP_";
    public static final String REDIS_KEY_TOKEN_PREFIX="LOGIN_TOKEN_";



    /**
     * 用户登录
     * @param param
     * @return
     */
    public Map<String, String> login(Map<String, String> param) {

        //校验验证码
        String verificationCode = param.get("verificationCode");
        String uuid = param.get("uuid");
        //从redis中获取刚存入的验证码
        String code = redisTemplate.opsForValue().get(uuid);


        if (!StringUtils.equals(code, verificationCode)) {
            // 验证码已失效的提示信息
            return null;
        }
        //验证码使用之后进行删除
        redisTemplate.delete(uuid);
        //查询用户*/
        String username = param.get("username");
        String password = param.get("password");
        if (StrUtil.isAllBlank(username, password)) {
            //没有输入账号或密码
         log.error("请输入账号或者密码！");
        }
        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        Login adminLogin = loginMapper.selectOne(queryWrapper);
       // System.out.println(userLogin);
        if (adminLogin == null) {
            // 账号或密码有误
            return null;
        }

        //生成token
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", adminLogin.getId());
        claims.put("username", adminLogin.getUsername());
        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();
        //将token存入redis中
        redisTemplate.opsForValue().set(token, "3699", Duration.ofMinutes(600));
        Map<String, String> tokenMap = new HashMap<>();
        System.out.println(token);
        tokenMap.put("token", token);
        System.out.println(token);
        return tokenMap;

    }


    /**
     * 用户信息
     * @param token
     * @return
     */
    public static LoginVo QueryUserProfile(String token) {
        Login login = LoginThreadLocal.get();
        if(login==null){
            return null;
        }
        // 封装用户信息
        LoginVo loginVo = new LoginVo();

        loginVo.setUid(login.getId());
        loginVo.setUsername(login.getUsername());
        loginVo.setAvatar(null);
        return loginVo;
    }

    /**
     * 用户登出
     * @param token
     * @return
     */
    public ResponseEntity logout(String token) {
        String key = REDIS_KEY_TOKEN_PREFIX + token;
        redisTemplate.delete(key);
        return ResponseEntity.ok(null);
    }


    public Login queryUserByToken(String token1) {
        try {
            String token = token1.replace("Bearer ", " ");
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            Long id = Long.valueOf(body.get("id").toString());
            //通过id查询Admin
            QueryWrapper<Login> queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", id);
            return this.loginMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error("token解析异常", e);
        }
        return null;
    }
}
